#include "hardware.h"
#include "type.h"
#include "ymodem.h"

int status = 0;

bool JumpApp(uint32_t appAddr) {
	uint32_t jumpAddr;
	JumpCallback cb;
	if (((*(__IO uint32_t*)appAddr) & 0x2FFE0000 ) == 0x20000000) {  
		jumpAddr = *(__IO uint32_t*) (appAddr + 4);  
		cb = (JumpCallback)jumpAddr;  
		__set_MSP(*(__IO uint32_t*)appAddr);  
		cb();
		return true;
	} 
	return false;
}

void PrintTip() {
   
    printf("----------GuanJin TECH----------\r\n");
	printf("[1].Start program\r\n");
	printf("[2].Update program\r\n");
	printf("[3].Set parameter\r\n");
	printf("----------------------------------\r\n");
}

int main() {
	int cnt = 0;
	ProcessStatus process;
	USART1_Config();

	TIM3_Init();
	PrintTip();
    printf("enter BOOT\r\n");
	while (1) {
		process = Get_YModem_Status();
		switch (process) {
			case WAIT_ENTER_SYSTEM:
				delay_ms(100);
				cnt++;
     
				if (cnt >= 50) {
					if (!JumpApp(ApplicationAddress)) {
                    
						printf("No program\r\n");
						PrintTip();
                    
						cnt = 0;
						Set_YModem_Status(WAIT_ENTER_SYSTEM);
					}
				}
				break;
			case START_PROGRAM:
              
                printf("start app\r\n");
             
				if (!JumpApp(ApplicationAddress)) {
                
					printf("No program\r\n");
                
					PrintTip();
					cnt = 0;
					Set_YModem_Status(WAIT_ENTER_SYSTEM);
				}
                printf("start app failed\r\n");
				break;
			case UPDATE_PROGRAM:
             
				printf("C\r\n");
              	//printf("send c now\r\n");

				delay_ms(1000);
				break;
			case SET_PARAMETER:
              
				printf("reserved for set addr,while not support now\r\n");
				PrintTip();
               
				cnt = 0;
				Set_YModem_Status(WAIT_ENTER_SYSTEM);
				break;
			case UPDATE_SUCCESS:
				printf("\r\nUpdate success\r\n");
				PrintTip();
				cnt = 0;
				Set_YModem_Status(WAIT_ENTER_SYSTEM);
				break;
			default:
				break;
		}
	}
}
